package com.leetcode.merci.lc110;

import com.leetcode.merci.TreeNode;

/**
 * Created by bowen on 2017/7/23.
 */
public class Solution {


    public boolean isBalanced(TreeNode root) {
        if(root==null)
            return true;
        return bcTree(root,0)!=-1;
    }

    public int bcTree(TreeNode node, int length) {
        if(node==null)
            return length;
        int left;
        int right;
        length++;
        if (node.right == null && node.left == null) {
            return length;
        }
            left = bcTree(node.left, length );
            if(left==-1){
                return -1;
            }
            right = bcTree(node.right, length);
            if(right==-1){
                return -1;
            }
        if(left-right<-1 ||left-right>1)
            return -1;
        return left>right?left:right;
    }

}
